<template>
  <!-- 标题表格 -->
  <!-- <el-table :data="[{ title: '排程排产数据' }]" style="margin-bottom: 10px" border>
    <el-table-column
      prop="title"
      label=""
      :show-overflow-tooltip="false"
    >
      <template #default="scope">
        <span style="font-size: 20px; font-weight: bold; color: #1976d2;">
          {{ scope.row.title }}
        </span>
      </template>
    </el-table-column>
  </el-table> -->
  <!-- 下面是你的同步栏、表单、数据表格等内容 -->
  <el-card class="card_outsides">
    <template #header>
      <div class="card-header">
        <span>排产数据</span>
      </div>
    </template>
    <div class="sync-bar">
      <el-button type="success" class="sync-btn" @click="syncData('current')">同步数据</el-button>
      <!-- <span class="sync-time"> 最近同步时间：{{ lastSyncTime || '--' }} </span> -->
      <!-- <div class="month-btns">
        <el-button :type="monthType === 'prev' ? 'primary' : 'default'" @click="syncData('prev')"
          >上个月</el-button
        >
        <el-button
          :type="monthType === 'current' ? 'primary' : 'default'"
          @click="syncData('current')"
          >当月</el-button
        >
        <el-button :type="monthType === 'next' ? 'primary' : 'default'" @click="syncData('next')"
          >下个月</el-button
        >
      </div> -->
    </div>
    <!-- 下面是表格等内容 -->
    <!-- <ContentWrap> -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
         style="margin: 20px 0 5px;"
      >
        <el-form-item label="订单号" prop="ordernumber">
          <el-input
            v-model="queryParams.ordernumber"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="工单号" prop="workordernumber">
          <el-input
            v-model="queryParams.workordernumber"
            placeholder="请输入工单号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <!--      <el-form-item label="日期" prop="date">-->
        <!--        <el-date-picker-->
        <!--          v-model="queryParams.date"-->
        <!--          value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--          type="daterange"-->
        <!--          start-placeholder="开始日期"-->
        <!--          end-placeholder="结束日期"-->
        <!--          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
        <!--          class="!w-220px"-->
        <!--        />-->
        <!--      </el-form-item>-->
        <!--      <el-form-item label="排产数量" prop="value">-->
        <!--        <el-input-->
        <!--          v-model="queryParams.value"-->
        <!--          placeholder="排产数量"-->
        <!--          clearable-->
        <!--          @keyup.enter="handleQuery"-->
        <!--          class="!w-240px"-->
        <!--        />-->
        <!--      </el-form-item>-->
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['scheduling:production:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['scheduling:production:export']"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>
    <!-- </ContentWrap> -->

    <!-- 列表 -->
    <!-- <ContentWrap> -->
      <el-table
        v-loading="loading"
        :data="tableData"
        :stripe="true"
        :show-overflow-tooltip="true"
        :header-cell-style="headerCellStyle"
        border
      >
        <el-table-column label="订单号" align="center" prop="ordernumber" />
        <el-table-column label="工单号" align="center" prop="workordernumber" />
        <el-table-column v-for="date in dateList" :key="date" :label="date" align="center">
          <template #default="scope">
            {{ scope.row.values[date] || '' }}
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    <!-- </ContentWrap> -->

    <!-- 表单弹窗：添加/修改 -->
    <ProductionForm ref="formRef" @success="getList" />
  </el-card>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { ProductionApi, ProductionVO } from '@/api/production'
import ProductionForm from './ProductionForm.vue'

/** Scheduling and production information table 列表 */
defineOptions({ name: 'Production' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ProductionVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const lastSyncTime = ref('') // 最近同步时间
const monthType = ref('current') // 当前选中的月份类型

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  ordernumber: undefined,
  workordernumber: undefined,
  month: '' // 传递给后端的月份参数，格式如 '2025-06'
  // 其他条件...
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const dateList = ref<string[]>([])
const tableData = ref<any[]>([])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductionApi.getProductionPage(queryParams)
    // 整理所有日期
    dateList.value = Array.from(new Set(data.list.map((item) => item.date.join('-')))).sort()
    // 转换表格数据
    const tableMap = new Map()
    data.list.forEach((item) => {
      const key = item.ordernumber + '|' + item.workordernumber
      const dateStr = item.date.join('-')
      if (!tableMap.has(key)) {
        tableMap.set(key, {
          ordernumber: item.ordernumber,
          workordernumber: item.workordernumber,
          values: {}
        })
      }
      tableMap.get(key).values[dateStr] = item.value
    })
    tableData.value = Array.from(tableMap.values())
    total.value = data.total
    // 设置最近同步时间（假设后端返回了 lastSyncTime 字段，否则用当前时间）
    lastSyncTime.value = data.lastSyncTime || new Date().toLocaleString()
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.month = '' // 清空月份
  monthType.value = '' // 取消高亮
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductionApi.deleteProduction(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductionApi.exportProduction(queryParams)
    download.excel(data, 'Scheduling and production information table.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 同步数据方法
const syncData = (type: 'prev' | 'current' | 'next') => {
  monthType.value = type
  // 计算要查询的月份
  const now = new Date()
  let targetMonth = now.getMonth() + 1
  let targetYear = now.getFullYear()
  if (type === 'prev') {
    targetMonth -= 1
    if (targetMonth === 0) {
      targetMonth = 12
      targetYear -= 1
    }
  } else if (type === 'next') {
    targetMonth += 1
    if (targetMonth === 13) {
      targetMonth = 1
      targetYear += 1
    }
  }
  // 格式化月份
  queryParams.month = `${targetYear}-${targetMonth.toString().padStart(2, '0')}`
  getList()
}

/** 初始化 **/
onMounted(() => {
  // 页面初始化默认查当月
  syncData('current')
})

// 设置表头样式：只有日期列变黄
const headerCellStyle = ({ columnIndex }) => {
  // 前两列不变，后面动态日期列变黄
  if (columnIndex >= 2) {
    return {
      background: '#FFA500', // 橙黄色
      color: '#fff',
      fontWeight: 'bold'
    }
  } else {
    return {
     background: '#f5f7fa', 
     color: '#606266', 
     textAlign: 'center' 
       
    }
  }
}
</script>

<style scoped lang="scss">
.sync-bar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.sync-btn {
  background: #b6e03e;
  color: #fff;
  border: none;
  margin-right: 10px;
}
.sync-time {
  /* border: 1px solid #f00; */
  color: #333;
  padding: 2px 8px;
  margin-right: auto;
  margin-left: 5px;
}
.month-btns {
  /* border: 1px solid #f00; */
  border-radius: 4px;
  padding: 2px 4px;
  display: flex;
  gap: 2px;
}
.month-btns .el-button--primary {
  background: #009cff;
  color: #fff;
}
</style>
